package org.thesis.secutity;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Log;
public class KeyManager 
{
	KeyGenerator Keygen;
    SecretKey Key;
    FileOutputStream fos;
    FileInputStream fis;
    //thong tin ve key
    String Mahoa;
    int sizeKey;
    String output;
    
    String tag = "KeyManager";
    

    public KeyManager() {
		super();
		// TODO Auto-generated constructor stub
	}
    
    public void createRSAkey(String keyPu, String keyPri)
    {
    	try 
    	{
    		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    	    kpg.initialize(512);
    	    KeyPair kp = kpg.genKeyPair();

    	    KeyFactory fact = KeyFactory.getInstance("RSA");
    	    RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
    	    RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);

    	    saveToFile(keyPu, pub.getModulus(),pub.getPublicExponent());
    	    saveToFile(keyPri, priv.getModulus(),priv.getPrivateExponent());
    	    Log.v(tag, "tao cap ket RSA thanh cong");
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi tao cap key RSA");
		}
    }
    public void saveToFile(String fileName,BigInteger mod, BigInteger exp)
    {
    	try 
    	{
    		ObjectOutputStream oout = new ObjectOutputStream(
    			    new BufferedOutputStream(new FileOutputStream(fileName)));
    		oout.writeObject(mod);
    	    oout.writeObject(exp);
    	    oout.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi save file");
		}
    }

	public String taoKey(String LoaiMaHoa, int chieudaikhoa, String path) //LoaiMaHoa :DES, DESede, AES
    {
        String s = "";
        try
        {
            // tao key
           Keygen = KeyGenerator.getInstance(LoaiMaHoa);//tao key loai nao
           Keygen.init(chieudaikhoa);
           Key = Keygen.generateKey();
           //lưu key
           fos = new FileOutputStream(path);
           byte []encodeKey = Key.getEncoded();
           fos.write(encodeKey);
           fos.close();
            // show thong tin ve Key vua tao
           System.out.println("*********************************************");
           System.out.println(s += "Thông tin về Key vừa tạo");
           s += "\n";
           System.out.println(s += "Loại mã hóa : " + Keygen.getAlgorithm());
           s += "\n";
           System.out.println(s +="Cơ quan cung cấp : " + Keygen.getProvider());
           s += "\n";
           System.out.println(s +="Chiều dài Key : "  + chieudaikhoa);
           s += "\n";
           System.out.println(s +="Format : " + Key.getFormat());
           s += "\n";
           System.out.println(s +="Nơi lưu key :" + path);
           s += "\n";
           System.out.println(s +="Tostring :" + encodeKey.toString());
           s += "\n";

        }
        catch(Exception e)
        {
           Log.v(path, "loi tao key "+ e.toString() );
        }
        return s;
    }

    public SecretKeySpec getKeyAES(String pathinput)
    {
        SecretKeySpec KeySpec = null;
        try
        {
            //doc file Key
            fis = new FileInputStream(pathinput);
            byte []encodeKey = new byte[fis.available()];
            fis.read(encodeKey);
            fis.close();
            //
            KeySpec = new SecretKeySpec(encodeKey,"AES");
                ///
                System.out.println("#############################");
               System.out.println("Thông tin về Key vừa Đoc");
               System.out.println("Loại mã hóa : " + KeySpec.getAlgorithm());
               System.out.println("Cơ quan cung cấp : " );
               System.out.println("Chiều dài Key : "  );
               System.out.println("Format : " + KeySpec.getFormat());
               System.out.println("Nơi lưu key :" + pathinput);
               System.out.println("Tostring :" + encodeKey.toString());
            

        }
        catch(Exception e)
        {
            Log.v(tag,  "Loi Doc Key "+e.toString());
        }
        return KeySpec;
    }

    //doc key DES
    public SecretKey getKeyDES(String path)
    {
        SecretKey KeyDES = null;
        try
        {
            //doc file Key
            fis = new FileInputStream(path);
            byte []encodeKey = new byte[fis.available()];
            fis.read(encodeKey);
            fis.close();
            //
            KeySpec mykeyspec = new DESKeySpec(encodeKey);
            SecretKeyFactory myKeyfactory = SecretKeyFactory.getInstance("DES");
            KeyDES = myKeyfactory.generateSecret(mykeyspec);
        }
        catch(Exception e)
        {
        	 Log.v(tag, "Loi Doc Key DES "+e.toString());
        }
        return KeyDES;
    }
    public SecretKeySpec getKey3DES(String path)
    {
        SecretKeySpec KeySpec = null;
        try
        {
            fis = new FileInputStream(path);
            byte[]encodeKey = new byte[fis.available()];
            fis.read(encodeKey);
            fis.close();
            KeySpec = new SecretKeySpec(encodeKey, "TripleDES");
            System.out.println("#############################");
               System.out.println("Thông tin về Key vừa Đoc");
               System.out.println("Loại mã hóa : " + KeySpec.getAlgorithm());
               System.out.println("Cơ quan cung cấp : " );
               System.out.println("Chiều dài Key : "  );
               System.out.println("Format : " + KeySpec.getFormat());
               System.out.println("Nơi lưu key :" + path);
               System.out.println("Tostring :" + encodeKey.toString());
        }
        catch(Exception e)
        {
        	 Log.v(tag, "Loi Doc Key "+e.toString());
        }
        return KeySpec;
    }

}
